<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-04-19 14:18:12
 * @LastEditTime: 2022-04-19 17:23:07
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 策略模式
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>策略模式</title>
</head>

<body>
</body>
<script>
  /*   // 策略A
    function StrategyA(salary) { }
    StrategyA.prototype.calculate = function (salary) {
      return salary * 3
    }
    // 策略B
    function StrategyB(salary) { }
    StrategyB.prototype.calculate = function (salary) {
      return salary * 2
    }
    // 策略C
    function StrategyC(salary) { }
    StrategyC.prototype.calculate = function (salary) {
      return salary * 1
    }
  
    // 奖金
    function Bonus(salary, strategy) {
      this.salary = 0
      this.strategy = null
    }
    Bonus.prototype.setSalary = function (salary) {
      this.salary = salary
    }
    Bonus.prototype.setStrategy = function (strategy) {
      this.strategy = strategy
    }
    Bonus.prototype.getBonus = function () {
      return this.strategy.calculate(this.salary)
    }
    const b1 = new Bonus()
    b1.setSalary(10000)
    b1.setStrategy(new StrategyA())
    console.log(b1.getBonus());
  
    const b2 = new Bonus()
    b2.setSalary(30000)
    b2.setStrategy(new StrategyC())
    console.log(b2.getBonus()); */


  /* // ES6 改写
     class StrategyA {
      calculate(salary) {
        return salary * 3
      }
    }
    class StrategyB {
      calculate(salary) {
        return salary * 2
      }
    }
    class StrategyC {
      calculate(salary) {
        return salary * 1
      }
    }
    class Bonus {
      constructor(strategy, salary) {
        this.strategy = strategy
        this.salary = salary
      }
      setSalary(salary) {
        this.salary = salary
      }
      setStrategy(strategy) {
        this.strategy = strategy
      }
      getBonus() {
        return this.strategy.calculate(this.salary)
      }
    }
    const b1 = new Bonus()
    b1.setSalary(10000)
    b1.setStrategy(new StrategyA)
    console.log(b1.getBonus());
  
    const b2 = new Bonus()
    b2.setSalary(30000)
    b2.setStrategy(new StrategyC)
    console.log(b2.getBonus()); */

  // 不使用面向对象
  const strategies = {
    'A': (salary) => salary * 3,
    'B': (salary) => salary * 2,
    'C': (salary) => salary * 1
  }
  function bonus(salary,strategy){
    return strategies[strategy](salary)
  }
  console.log(bonus(10000, 'A'));

</script>

</html>